package com.yantu.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yantu.bean.*;
import com.yantu.mapper.ExamPaperMapper;
import com.yantu.mapper.QuestionMapper;
import com.yantu.mapper.TextContentMapper;
import com.yantu.mapper.UserEventLogMapper;
import com.yantu.util.RedisUtils;
import com.yantu.util.Result;
import com.yantu.view.admin.AdminPageView;
import com.yantu.view.admin.addPaper.AdminPaperView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 综合实训课程设计
 * @since 2022-08-13
 */
@RestController
@RequestMapping("/admin")
@Api("管理端试卷接口")
public class AdminExamPaperController extends AdminUserEventLogController{

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    ExamPaperMapper examPaperMapper;
    @Autowired
    TextContentMapper textContentMapper;
    @Autowired
    QuestionMapper questionMapper;

    //试卷列表分页
    @GetMapping("/examPapers")
    @ApiOperation("试卷分页信息")
    public Result myListExamPaper(@ModelAttribute AdminPageView pageView){
        PageHelper.startPage(pageView.getPageIndex(),pageView.getPageSize());
        if(redisUtils.haskeysf("adminPaperList"+pageView)){
            System.out.println("缓存里面有");
            PageInfo pageInfo = ( PageInfo) redisUtils.getValue("adminPaperList"+pageView);
            return Result.succ(200, "查询成功", pageInfo);
        }else {
            QueryWrapper<ExamPaper> queryWrapper = new QueryWrapper<>();
            if (pageView.getId() != null) {
                queryWrapper.eq("id", pageView.getId());
            }
            if (pageView.getLevel() != null) {
                queryWrapper.eq("level", pageView.getLevel());
            }
            if (pageView.getSubjectId() != null) {
                queryWrapper.eq("subject_id", pageView.getSubjectId());
            }
            List<ExamPaper> examPaperList = examPaperMapper.selectList(queryWrapper);
            PageInfo pageInfo = new PageInfo(examPaperList);
            redisUtils.saveValue("adminPaperList"+pageView,pageInfo);
            return Result.succ(200, "查询成功", pageInfo);
        }
    }

    //试卷查询
    //试卷查询
    @GetMapping("/examPaper/{id}")
    @ApiOperation("根据试卷id查询试卷")
    public Result paperSelect(@PathVariable("id") Integer id) {
        if(redisUtils.haskeysf("adminPaper"+id)){
            System.out.println("缓存里面有");
            Map map= (Map) redisUtils.getValue("adminPaperList"+id);
            return Result.succ(200, "查询成功", map);
        }else {
            ExamPaper examPaper = examPaperMapper.selectById(id);
            //每一张试卷
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", examPaper.getId());
            map.put("level", examPaper.getGradeLevel());
            map.put("subjectId", examPaper.getSubjectId());
            map.put("paperType", examPaper.getPaperType());
            map.put("name", examPaper.getName());
            map.put("suggestTime", examPaper.getSuggestTime());
            map.put("limitDateTime", null);


            List<Object> list1 = new ArrayList();

            //将Exam_paper表和text_content对应起来
            TextContent textContent = textContentMapper.selectById(examPaper.getFrameTextContentId());
            //获取content表中的content内容
            //"titleItems"
            //JSONArray(list类型)
            //JSONObject（Map类型）
            JSONArray contentArray = JSONArray.fromObject(textContent.getContent());
            //大题
            for (int k = 0; k < contentArray.size(); k++) {
                HashMap<String, Object> map1 = new HashMap<>();
                JSONObject content = contentArray.getJSONObject(k);
                map1.put("name", content.getString("name"));
                List<Object> list2 = new ArrayList();
                //获取大标题内的题目列表
                // "questionItems"
                JSONArray questionItemArray = JSONArray.fromObject(content.getString("questionItems"));
                //小题的Map--map2
                for (int i = 0; i < questionItemArray.size(); i++) {
                    JSONObject qusetion = questionItemArray.getJSONObject(i);
                    HashMap<String, Object> map2 = new HashMap<>();
                    map2.put("id", qusetion.getString("id"));
                    map2.put("itemOrder", qusetion.getString("itemOrder"));
                    Question questionItem = questionMapper.selectById(qusetion.getString("id"));
                    map2.put("questionType", questionItem.getQuestionType());
                    map2.put("subjectId", questionItem.getSubjectId());
                    map2.put("score", questionItem.getScore());
                    map2.put("gradeLevel", questionItem.getGradeLevel());
                    map2.put("difficult", questionItem.getDifficult());
                    map2.put("correct", questionItem.getCorrect());
                    String[] answer = questionItem.getCorrect().split(",");
                    List<String> correctList = new ArrayList<>();
                    for (int j = 0; j < answer.length; j++) {
                        correctList.add(answer[j]);
                    }
                    map2.put("correctArray", correctList);
                    if (questionItem.getInfoTextContentId() != null) {
                        TextContent textContent1 = textContentMapper.selectById(questionItem.getInfoTextContentId());
                        JSONObject content1 = JSONObject.fromObject(textContent1.getContent());
                        map2.put("title", content1.getString("titleContent"));
                        map2.put("analyze", content1.getString("analyze"));
                        JSONArray contentObject1 = JSONArray.fromObject(content1.getString("questionItemObjects"));
                        List<Object> answList = new ArrayList<>();
                        if (contentObject1.size() == 0) {
                            map2.put("questionItemObjects", null);
                        } else {
                            for (int j = 0; j < contentObject1.size(); j++) {
                                JSONObject xuanxiang = contentObject1.getJSONObject(i);
                                Map<String, String> map4 = new HashMap();
                                map4.put("prefix", xuanxiang.getString("prefix"));
                                map4.put("content", xuanxiang.getString("content"));
                                map4.put("score", xuanxiang.getString("score"));
                                answList.add(map4);
                            }
                            map2.put("questionItemObjects", answList);
                        }
                    }
                    //小题List
                    list2.add(map2);
                }
                //大题Map
                map1.put("questionItems", list2);
                //大题List
                list1.add(map1);
            }
            map.put("titleItems", list1);
            map.put("score", examPaper.getScore());
            redisUtils.saveValue("adminPaperList"+id,map);
            return Result.succ(200, "查询成功", map);
        }
    }

    //试卷编辑
    @PutMapping("/examPaper")
    @ApiOperation("编辑试卷信息")
    public Result editExamPaper(@ModelAttribute AdminPaperView paperView){
        ExamPaper examPaper=examPaperMapper.selectById(paperView.getId());
        System.out.println("查询到要修改的试卷了"+examPaper);
        TextContent textContent=textContentMapper.selectById(examPaper.getFrameTextContentId());
        System.out.println("查询到试卷对应的content了"+textContent);
        //将接收的content转为字串
        JSONArray jsonArray=JSONArray.fromObject(paperView.getBigTitleViews());
        UpdateWrapper updateWrapper=new UpdateWrapper<>();
        //设置content更新体
        updateWrapper.eq("id",textContent.getId());
        updateWrapper.set("content",jsonArray.toString());
        int result=textContentMapper.update(null,updateWrapper);
        if(result>0){
            System.out.println("content内容修改成功");
            UpdateWrapper updateQuery=new UpdateWrapper<>();
            updateQuery.eq("id",paperView.getId());
            updateQuery.set("grade_level",paperView.getGradeLevel());
            updateQuery.set("subject_id",paperView.getSubjectId());
            updateQuery.set("paper_type",paperView.getPaperType());
            updateQuery.set("name",paperView.getName());
            updateQuery.set("suggest_time",paperView.getSuggestTime());
            updateQuery.set("score",paperView.getScore());
            updateQuery.set("question_count",paperView.getQuestionCount());
            updateQuery.set("limit_start_time",paperView.getLimitStartTime());
            updateQuery.set("limit_end_time",paperView.getLimitEndTime());
            int result1=examPaperMapper.update(null,updateQuery);
            if(result1>0){
                super.adminLog("admin修改了试卷"+paperView.getId());
                redisUtils.delAll();
                return Result.succ(200,"编辑成功",null);
            }else {
                return Result.fail("编辑失败");
            }
        }else {
            return Result.fail("编辑失败");
        }


    }

    //试卷删除
    @DeleteMapping("/examPaper/{id}")
    @ApiOperation("删除试卷")
    public Result deleteExamPaper(@PathVariable("id") Integer id) {
        int result = examPaperMapper.deleteById(id);
        if(result>0){
            //删除试卷的日志
            super.adminLog("admin删除了试卷"+id);
            redisUtils.delAll();
            return Result.succ("删除成功",null);
        }else {
            return Result.fail("删除失败");
        }
    }
}

